package com.qf.demo.conf;


import com.qf.demo.filter.KaptchaFilter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.security.web.authentication.rememberme.JdbcTokenRepositoryImpl;
import org.springframework.security.web.authentication.rememberme.PersistentTokenRepository;

import javax.sql.DataSource;

@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private MyLogoutSuccessHandler myLogoutSuccessHandler;

    @Qualifier("UserDetail")
    @Autowired
    private UserDetailsService userDetailsService;

    @Autowired
    private DataSource dataSource;

    @Autowired
    private PersistentTokenRepository persistentTokenRepository;



    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder());
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.formLogin()
                .loginPage("/login.html")
                .usernameParameter("phone_number")
                .loginProcessingUrl("/login")
                .successForwardUrl("/user/success")
                .failureForwardUrl("/user/fail");
//                .successHandler(mySuccess);


        http.authorizeRequests()//对所有请求开启认证
                .antMatchers("/prod/**").hasAuthority("admin")
                .antMatchers("/","/user/regist","/login.html","/login","/code/**","/user/fail").permitAll()
            //设置可以直接访问的路径，取消拦截
                .anyRequest().authenticated();

        http.rememberMe().userDetailsService(userDetailsService)
//                .tokenValiditySeconds(60)  // 默认为两周免登录
//                .rememberMeParameter("remember-me")
                .tokenRepository(persistentTokenRepository);

        //在认证用户名之前认证验证码，如果验证码错误，将不执行用户名和密码的认证
        http.addFilterBefore(new KaptchaFilter("/login", "/login?error"), UsernamePasswordAuthenticationFilter.class);
        //注销的配置
        http.logout().logoutUrl("/logout") //注销时访问的路径
                .logoutSuccessHandler(myLogoutSuccessHandler);



        http.csrf().disable(); //关闭csrf防护

    }
    @Bean
    PasswordEncoder passwordEncoder(){
        return new BCryptPasswordEncoder();
    }

    @Bean
    public PersistentTokenRepository getPersistentTokenRepository(){
        JdbcTokenRepositoryImpl jdbcTokenRepository = new JdbcTokenRepositoryImpl();
        jdbcTokenRepository.setDataSource(dataSource);
//        jdbcTokenRepository.setCreateTableOnStartup(true);
        return jdbcTokenRepository;
    }
}
